import React, {useEffect, useMemo, useState} from "react";
import {getTrafficForecastChartUsingPost} from "@/services/api-backend/trafficForecastController";
import ReactECharts from "echarts-for-react";
import {Button, Card, Col, DatePicker, Form, message, Row, Select, Space, Switch} from "antd";
import moment from "moment";
// 查询类型选项
const queryTypeOptions = [
  { label: '历史数据', value: 'historical' },
  { label: '预测数据', value: 'forecast' },
  { label: '全部', value: 'all' },
];

// 时间粒度选项
const timeGranularityOptions = [
  { label: '分钟', value: 'minute' },
  { label: '小时', value: 'hour' },
  { label: '天', value: 'day' },
];

// 模型类型选项
const modelTypeOptions = [
  { label: 'Prophet', value: 'prophet' },
  { label: 'LSTM', value: 'lstm' },
  { label: 'ARIMA', value: 'arima' },
  { label: '集成模型', value: 'ensemble' },
];

export type Props = {
  infoVo: {id: number, name: string}[];
  type?:number
};
export  const TrafficForecastChart:React.FC<Props>=(props)=>{
  const {infoVo,type}=props
  const [interfaceNameList,setInterfaceNameList]=useState<{value: number, label: string}[]>([])
  const [data ,setData]=useState<API.TrafficForecastChartVO>()
  const [loading,setLoading]=useState<boolean>(false)
  const [formRef] = Form.useForm();
  const [currentId,setCurrentId]=useState<number>()
  const formInitValues={
    queryType: 'all',
    timeGranularity: 'day',
    modelType: 'prophet',
    includeConfidence: true,
    timeRange:[
      moment().subtract(7, 'days'),
      moment().add(1,"day")
    ]
  }
  useEffect(() => {
    if(infoVo&&infoVo.length>0){
      const items=infoVo.map(item=>({
        value:item.id!,
        label:item.name
      }))
      loadData({interfaceId:infoVo[0]?.id,...formInitValues})
      // 数据加载完成后设置表单默认值
      formRef.setFieldsValue({ interfaceId: items[0]?.value })
      setInterfaceNameList(items)
    }
  }, [infoVo]);

    const loadData=async (values:API.TrafficForecastQueryRequest)=>{
      setLoading(true)
    try {
        const body={...values}
      const params={type}

      const {data}=await  getTrafficForecastChartUsingPost(params,body)
      if(data){
        setTimeout(()=> setData(data),2300)
      }
      setCurrentId(body.interfaceId)
    }catch (error){
      message.error('流量预测查询失败,',error)
    }finally {
      setTimeout(()=> setLoading(false),3000)
    }
  }

  const doSubmit=async (values)=>{
    if(!values&&!values?.interfaceId){
      message.warning("流量预测必须填写接口id")
      return
    }

    var startTime=null
    var endTime=null

    if(values.timeRange){
      startTime=values.timeRange[0]
      endTime=values.timeRange[1]
    }

    await loadData({
      ...values,
      startTime,
      endTime,
      queryType:"all"
    })

  }

  const doReset=async ()=>{
      const  timeRange=[
            moment().subtract(7, 'days'),
          moment().add(1,"day")
      ]
      const params={
        ...formInitValues,
        interfaceId:currentId,
        timeRange
      }
      await loadData(params)
      formRef.setFieldsValue({interfaceId:currentId,timeRange})
  }

  // 使用 useMemo 动态生成 ECharts 配置
  const option = useMemo(() => {
    if (!data) {
      return {
        title: { text: '流量预测' },
        xAxis: { type: 'category', data: [] },
        yAxis: { type: 'value', name: '请求数' },
        series: []
      };
    }

    const series: any[] = [
      {
        name: '实际流量',
        type: 'line',
        data: data.actualValues,
        itemStyle: { color: '#5470c6' },
        markLine: data.splitIndex ? {
          silent: true,
          lineStyle: { color: '#999', type: 'dashed', width: 2 },
          label: { show: true, position: 'end', formatter: '历史/预测分界' },
          data: [{ xAxis: data.splitIndex - 1 }] // 修正索引
        } : undefined
      },
      {
        name: '预测流量',
        type: 'line',
        data: data.predictedValues,
        itemStyle: { color: '#ee6666' },
        lineStyle: { type: 'dashed' }
      }
    ];

    // 如果包含置信区间，添加置信区间区域
    if (data.confidenceUpper && data.confidenceLower ) {
      // 下界线（隐藏，仅用于区域计算）
      series.push({
        name: '置信区间下界',
        type: 'line',
        data: data.confidenceLower,
        lineStyle: { opacity: 0 },
        stack: 'confidence',
        symbol: 'none'
      });

      // 上界线（用于填充区域）
      series.push({
        name: '置信区间上界',
        type: 'line',
        data: data.confidenceUpper,
        lineStyle: { opacity: 0 },
        areaStyle: {
          color: 'rgba(238, 102, 102, 0.2)'
        },
        stack: 'confidence',
        symbol: 'none'
      });
    }

    return {
      title: {
        text: `${data.interfaceName || ''} 流量预测`
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
      },
      legend: {
        data: data.confidenceUpper && data.confidenceLower ?
          ['实际流量', '预测流量', '置信区间'] :
          ['实际流量', '预测流量']
      },
      xAxis: {
        type: 'category',
        data: data.timeLabels,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        name: '请求数'
      },
      series
    };
  }, [data]);

  return <>

    {/*<Collapse*/}
    {/* defaultActiveKey={['1']}*/}
    {/* style={{marginBottom:24,background: token.colorBgContainer }}*/}
    {/* items={[*/}
    {/*  {*/}
    {/*    key:"1",*/}
    {/*    label:"查询条件",*/}
    {/*    children:<>*/}

    {/*    </>*/}
    {/*  }*/}

    {/*]} />*/}
    <Card style={{marginBottom:24}}>
      <Form
        form={formRef}
        layout="inline"
        onFinish={doSubmit}
        onReset={doReset}
        initialValues={formInitValues}
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8} lg={6}>
            <Form.Item
              label="接口"
              name="interfaceId"
              rules={[
                {
                  required: true,
                  message: "接口不能为空"
                }]}
            >
              <Select

                placeholder={"请选择接口"}
                allowClear
                style={{ width: 220 }}
                options={interfaceNameList}></Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={24} md={12} lg={10}>
            <Form.Item
              label="时间范围"
              name="timeRange"
            >
              <DatePicker.RangePicker
                showTime={{ format: 'HH:mm:ss' }}
                format="YYYY-MM-DD HH:mm:ss"
                placeholder={['开始时间', '结束时间']}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>

          {/*<Col xs={26} sm={14} md={10} lg={8}>*/}
          {/*  <Form.Item*/}
          {/*    label="查询类型"*/}
          {/*    name="queryType"*/}
          {/*  >*/}
          {/*    <Radio.Group options={queryTypeOptions} />*/}
          {/*  </Form.Item>*/}
          {/*</Col>*/}

          <Col xs={24} sm={12} md={8} lg={6}>
            <Form.Item
              label="时间粒度"
              name="timeGranularity"
            >
              <Select placeholder="请选择时间粒度" style={{ width: '100%' }}>
                {timeGranularityOptions.map(opt => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            <Form.Item
              label="模型类型"
              name="modelType"
            >
              <Select placeholder="请选择模型类型" style={{ width: '100%' }}>
                {modelTypeOptions.map(opt => (
                  <Option key={opt.value} value={opt.value}>{opt.label}</Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            <Form.Item
              label="包含置信区间"
              name="includeConfidence"
              valuePropName="checked"
            >
              <Switch  loading={loading} checkedChildren="是" unCheckedChildren="否" />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            {/* 提交按钮 */}
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  查询
                </Button>
                <Button htmlType="reset" disabled={loading}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>

    </Card>
    <ReactECharts    showLoading={loading} option={option}/>
  </>
}
